package test;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by Connor Madden.
 * User: Connor Madden
 * Date: 20/08/11
 * Time: 4:26 PM
 */
public class Dispatch implements Observer {
    private static final int STEP_TIME = 1000;
    Lift lift;
    Scheduler scheduler;
    private static final int EXCHANGE_TIME = 4000;

    public Dispatch(Lift lift) {
        this.lift = lift;
        this.lift.addObserver(this);
        scheduler = new Scheduler();
    }

    public void update(Observable o, Object arg) {
        if (o.getClass() == Lift.class && arg == Lift.Change.LOC_CHANGE) {
            arrive();
        }
    }

    public void move() {
        if (scheduler.hasDestination()) {
            // wait STEP_TIME then move lift
            new Thread(new Timer(STEP_TIME, new Observer() {
                public void update(Observable o, Object arg) {
                    lift.move(scheduler.getStep(lift));
                }
            })).start();
        }
    }

    public void arrive() {
        int liftLoc = lift.getLoc();
        int liftDir = lift.getLastDir();
        // if at stop
        if (scheduler.isStop(liftLoc, liftDir)) {
            lift.openDoor();
            scheduler.removeCall(liftLoc, liftDir);
            scheduler.removeDisembark(liftLoc);
            // wait EXCHANGE_TIME then close door
            new Thread(new Timer(EXCHANGE_TIME, new Observer() {
                public void update(Observable o, Object arg) {
                    lift.closeDoor();
                    move();
                }
            })).start();
        } else move();
    }

    public void addCall(int loc, int dir) {
        scheduler.addCall(loc, dir);
        move();

    }

    public void addDisembark(int loc) {
        scheduler.addDisembark(loc);
        System.out.println("Disembark: " + scheduler.disembarkLoc.toString());
        move();
    }
}
